const { createServer } = require('http');
const { Server } = require("socket.io")

const httpServer = createServer();

const io = new Server(httpServer, {
    cors: true
})

const groupMap = {};
io.on("connection", (socket) => {
    console.log("连接成功");
    // 1. 监听加入房间
    socket.on("join", (({ name, room }) => {
        socket.join(room); //创建一个房间

        // 2. 组装一个格式，给客户端
        if (groupMap[room]) {
            groupMap[room].push({ name, room, id: socket.id })
        } else {
            groupMap[room] = [{ name, room, id: socket.id }]
        }
        io.emit("groupMap", groupMap); // 发送给全部用户
        // socket.emit("groupMap", groupMap); //单独发给特定的用户
        // socket.broadcast.emit("groupMap", groupMap);//广播播放(会排除当前用户)，所有人都能看到

        io.emit("message", {
            name: "管理员",
            message: `${name} 加入聊天室`
        })

    }))
    // 接收用户信息
    socket.on("message", ({ name, message, room }) => {
        io.to(room).emit("message", { name, message })
    })
})

io.on("disconnect", () => {
    console.log("断开连接");
})

io.on("error", (err) => {
    console.log("发生错误", err);
})
httpServer.listen(3000, () => {
    console.log("server is running at 3000");
})